﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Waker.Common;
using Waker.Entitys;
using System.IO;
using System.Drawing.Imaging;

namespace Waker.Cards
{
    public partial class FormStaffImport : Base.FormBasePop
    {
        public FormStaffImport()
        {
            InitializeComponent();
        }
        Dictionary<string, int> _DicNation = new Dictionary<string, int>();
        Dictionary<string, int> _DicEdu = new Dictionary<string, int>();
        Dictionary<string, int> _DicJob = new Dictionary<string, int>();
        Dictionary<string, int> _DicWorkType = new Dictionary<string, int>();
        private void FormStaffImport_Load(object sender, EventArgs e)
        {
            var dtSite = new BAL.BAL_Cards().GetAllDepartment();
            ControlUtil.FillImageComboBox(dtSite, icbDept_ID, "Dept_Name", "Dept_ID");

            //ricbSex.Items.Add(new DevExpress.XtraEditors.Controls.ImageComboBoxItem("男", Convert.ToByte(1), -1));
            //ricbSex.Items.Add(new DevExpress.XtraEditors.Controls.ImageComboBoxItem("女", Convert.ToByte(0), -1));

            var dtNation = new BAL.BAL_SystemSetting().GetTableByTableName("tbEmp_Nation");
            //ControlUtil.FillImageComboBox(dtNation, ricbNation, "Nation_Name", "Nation_ID");
            if (dtNation != null && dtNation.Rows.Count > 0)
            {
                foreach (DataRow dr in dtNation.Rows)
                {
                    if (dr["Nation_Name"] != DBNull.Value && dr["Nation_ID"] != DBNull.Value && !_DicNation.Keys.Contains(dr["Nation_Name"].ToString()))
                        _DicNation.Add(dr["Nation_Name"].ToString(), Convert.ToInt32(dr["Nation_ID"]));
                }
            }


            var dtEdu = new BAL.BAL_SystemSetting().GetTableByTableName("tbEmp_Education");
            //ControlUtil.FillImageComboBox(dtEdu, ricbEdu, "Edu_Name", "Edu_ID");
            if (dtEdu != null && dtEdu.Rows.Count > 0)
            {
                foreach (DataRow dr in dtEdu.Rows)
                {
                    if (dr["Edu_Name"] != DBNull.Value && dr["Edu_ID"] != DBNull.Value && !_DicEdu.Keys.Contains(dr["Edu_Name"].ToString()))
                        _DicEdu.Add(dr["Edu_Name"].ToString(), Convert.ToInt32(dr["Edu_ID"]));
                }
            }

            var dtBaseDataJob = new BAL.BAL_SystemSetting().GetAllBaseDataByDataType(Enums.BaseDataType.Job);
            //ControlUtil.FillImageComboBox(dtBaseDataJob, ricbJob, "DataName", "ID");
            if (dtBaseDataJob != null && dtBaseDataJob.Rows.Count > 0)
            {
                foreach (DataRow dr in dtBaseDataJob.Rows)
                {
                    if (dr["DataName"] != DBNull.Value && dr["ID"] != DBNull.Value && !_DicJob.Keys.Contains(dr["DataName"].ToString()))
                        _DicJob.Add(dr["DataName"].ToString(), Convert.ToInt32(dr["ID"]));
                }
            }

            var dtBaseDataWorkType = new BAL.BAL_SystemSetting().GetAllBaseDataByDataType(Enums.BaseDataType.WorkType);
            //ControlUtil.FillImageComboBox(dtBaseDataWorkType, ricbWorkType, "DataName", "ID");
            if (dtBaseDataWorkType != null && dtBaseDataWorkType.Rows.Count > 0)
            {
                foreach (DataRow dr in dtBaseDataWorkType.Rows)
                {
                    if (dr["DataName"] != DBNull.Value && dr["ID"] != DBNull.Value && !_DicWorkType.Keys.Contains(dr["DataName"].ToString()))
                        _DicWorkType.Add(dr["DataName"].ToString(), Convert.ToInt32(dr["ID"]));
                }
            }
        }
        private void btnOpenFile_Click(object sender, EventArgs e)
        {
            base.errorPop.ClearErrors();
            if (icbDept_ID.EditValue == null)
            {
                base.errorPop.SetError(icbDept_ID, "请选择要导入的员工所属分包商");
                return;
            }
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "Office2003Excel文件|*.xls|Office2007Excel文件|*.xlsx";   //指定OpenFileDialog控件打开的文件格式 

            if (ofd.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            string picpath = ofd.FileName;
            try
            {
                StartWaiting();
                var dt = Util.ExcelToDataTableFirstSheet(ofd.FileName);
                if (dt == null || dt.Rows.Count < 1)
                {
                    UI.ShowError("Excel没有数据");
                    return;
                }
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    if (dt.Rows[0][i] != DBNull.Value)
                    {
                        if (dt.Rows[0][i].ToString().Contains("身份证"))
                        {
                            dt.Columns[i].ColumnName = "身份证号码";
                            continue;
                        }
                        if (dt.Rows[0][i].ToString().Contains("头像"))
                        {
                            dt.Columns[i].ColumnName = "头像";
                            continue;
                        }
                        dt.Columns[i].ColumnName = dt.Rows[0][i].ToString();
                    }
                }
                if (!dt.Columns.Contains("ErrTip"))
                {
                    dt.Columns.Add("ErrTip", typeof(string));
                }
                dt.Rows.RemoveAt(0);
                this.gridControl1.DataSource = dt;
                CheckData();
            }
            catch (Exception ex)
            {
                UI.ShowError(ex.Message);
            }
            finally
            {
                EndWaiting();
            }
        }


        protected override void FormSave()
        {
            try
            {
                StartWaiting();
                base.errorPop.ClearErrors();
                if (icbDept_ID.EditValue == null)
                {
                    base.errorPop.SetError(icbDept_ID, "请选择要导入的员工所属分包商");
                    return;
                }
                var dt = this.gridControl1.DataSource as DataTable;
                if (dt == null || dt.Rows.Count < 1)
                    return;

                if (!CheckData())
                {
                    UI.ShowError("数据有错,请检查后重试");
                    return;
                }

                if (!dt.Columns.Contains("Dept_ID"))
                    dt.Columns.Add("Dept_ID", typeof(string));

                if (!dt.Columns.Contains("Emp_jobID"))
                    dt.Columns.Add("Emp_jobID", typeof(Int32));
                if (!dt.Columns.Contains("Emp_nationId"))
                    dt.Columns.Add("Emp_nationId", typeof(Int32));
                if (!dt.Columns.Contains("Emp_eduId"))
                    dt.Columns.Add("Emp_eduId", typeof(Int32));
                if (!dt.Columns.Contains("WorkType"))
                    dt.Columns.Add("WorkType", typeof(Int32));

                if (!dt.Columns.Contains("Emp_Photo"))
                    dt.Columns.Add("Emp_Photo", typeof(byte[]));

                if (!dt.Columns.Contains("姓名"))
                {
                    dt.Columns.Add("姓名", typeof(string));
                }
                if (!dt.Columns.Contains("Emp_Sex"))
                {
                    dt.Columns.Add("Emp_Sex", typeof(byte));
                }
                foreach (DataRow dr in dt.Rows)
                {
                    dr["Dept_ID"] = icbDept_ID.EditValue.ToString();
                    if (dt.Columns.Contains("职位") && dr["职位"] != DBNull.Value && !string.IsNullOrEmpty(dr["职位"].ToString().Trim()) && _DicJob.Keys.Contains(dr["职位"].ToString()))
                        dr["Emp_jobID"] = _DicJob[dr["职位"].ToString().Trim()];

                    if (dt.Columns.Contains("民族") && dr["民族"] != DBNull.Value && !string.IsNullOrEmpty(dr["民族"].ToString().Trim()) && _DicNation.Keys.Contains(dr["民族"].ToString()))
                        dr["Emp_nationId"] = _DicNation[dr["民族"].ToString().Trim()];

                    if (dt.Columns.Contains("学历") && dr["学历"] != DBNull.Value && !string.IsNullOrEmpty(dr["学历"].ToString().Trim()) && _DicEdu.Keys.Contains(dr["学历"].ToString()))
                        dr["Emp_eduId"] = _DicEdu[dr["学历"].ToString().Trim()];

                    if (dt.Columns.Contains("工种") && dr["工种"] != DBNull.Value && !string.IsNullOrEmpty(dr["工种"].ToString().Trim()) && _DicWorkType.Keys.Contains(dr["工种"].ToString()))
                        dr["WorkType"] = _DicWorkType[dr["工种"].ToString().Trim()];

                    if (dt.Columns.Contains("性别") && dr["性别"] != DBNull.Value && !string.IsNullOrEmpty(dr["性别"].ToString().Trim()))
                    {
                        dr["Emp_Sex"] = Convert.ToByte(dr["性别"].ToString().Trim() == "男");
                    }
                    else
                        dr["Emp_Sex"] = 1;

                    if (dt.Columns.Contains("头像") && dr["头像"] != DBNull.Value && !string.IsNullOrEmpty(dr["头像"].ToString().Trim())
                        && File.Exists(dr["头像"].ToString().Trim())
                        )
                    {
                        dr["Emp_Photo"] = File.ReadAllBytes(dr["头像"].ToString().Trim());
                    }
                }


                int intRes = new BAL.BAL_Cards().ImportEmployee(dt);
                if (intRes > 0)
                {
                    UI.ShowInfo(string.Format("共{0}条数据,成功导入{1}位员工", dt.Rows.Count, intRes));
                    if (intRes == dt.Rows.Count)
                    {
                        this.DialogResult = DialogResult.OK;
                    }
                }
                else
                {
                    UI.ShowError("导入失败");
                }
            }
            catch (Exception ex)
            {
                UI.ShowError(ex.Message);
            }
            finally
            {
                EndWaiting();
            }
        }

        //private void gridView1_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        //{

        //    if (e.Column.FieldName == "姓名" || e.Column.FieldName == "性别")
        //    {
        //        if (e.CellValue == null || e.CellValue == DBNull.Value)
        //            e.Appearance.ForeColor = Color.Red;
        //        //base.errorPop.SetError(e.Column, "姓名不能为空");
        //    }
        //}

        private void btnCheckData_Click(object sender, EventArgs e)
        {
            CheckData();
        }

        private bool CheckData()
        {
            var dt = this.gridControl1.DataSource as DataTable;
            if (dt == null || dt.Rows.Count < 1)
                return false;
            var isOk = true;

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                isOk = CheckRowData(dt.Rows[i]);
            }
            return isOk;
            //for (int row = 0; row < gridView1.DataRowCount; row++)
            //{
            //    for (int i = 0; i < gridView1.Columns.Count; i++)
            //    { 

            //        var col=gridView1.Columns[i];
            //        gridView1.SelectCell(row, col);
            //      var cell=gridView1.GetSelectedCells()[0];
            //        object objValue= gridView1.GetFocusedRowCellValue(col.FieldName);
            //        switch(col.FieldName)
            //        {
            //            case "姓名":
            //             if( objValue  == DBNull.Value||objValue==null||string.IsNullOrEmpty(objValue.ToString()))
            //                 cell.r
            //                               break;
            //        }

            //    }
            //}
        }

        private void riBtnDel_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (gridView1.FocusedRowHandle < 0)
                return;
            var dr = gridView1.GetFocusedDataRow();
            if (dr == null)
                return;
            var dt = gridControl1.DataSource as DataTable;
            if (dt != null)
                dt.Rows.Remove(dr);
        }

        private void gridView1_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            var dr = gridView1.GetDataRow(e.RowHandle);
            if (dr == null)
                return;
            if (CheckRowData(dr))
                return;
            else
            {
                e.Appearance.ForeColor = Color.Red;
            }
        }
        bool CheckRowData(DataRow dr)
        {
            var bal = new BAL.BAL_Cards();
            var sbRes = new StringBuilder();
            var dt = dr.Table;
            if (!dt.Columns.Contains("姓名"))
            {
                sbRes.Append("|没有姓名列");
            }
            if (dt.Columns.Contains("姓名") && (dr["姓名"] == DBNull.Value || string.IsNullOrEmpty(dr["姓名"].ToString().Trim())))
            {
                //UI.ShowError(string.Format("第{0}行的姓名不能为空", i));
                sbRes.Append("|姓名不能为空");
                //return false;
            }
            if (dt.Columns.Contains("性别") && (dr["性别"] == DBNull.Value || string.IsNullOrEmpty(dr["性别"].ToString().Trim())))
            {
                //UI.ShowError(string.Format("第{0}行的性别不能为空", i));
                //return false;
                sbRes.Append("|性别不能为空");
            }
            if (dt.Columns.Contains("身份证号码") && dr["身份证号码"] != DBNull.Value && !string.IsNullOrEmpty(dr["身份证号码"].ToString().Trim()))
            {
                if (dr["身份证号码"].ToString().Trim().Length != 18)
                {
                    //UI.ShowError(string.Format("第{0}行的身份证号码不是18位", i));
                    //return false;
                    sbRes.Append("|身份证号码不是18位");
                }
                else
                {
                    if (dt.Select(string.Format("ISNULL([身份证号码],'')='{0}'", dr["身份证号码"].ToString().Trim())).Length > 1)
                    {
                        sbRes.Append("|身份证号码重复,请检查");
                    }
                    else
                    {
                        if (!bal.CheckEMployeeIDCardNo((dr["身份证号码"].ToString())))
                        {
                            sbRes.Append("|身份证号码已经存在");
                        }
                    }
                }
            }
            if (dt.Columns.Contains("职位") && dr["职位"] != DBNull.Value && !string.IsNullOrEmpty(dr["职位"].ToString()) && !_DicJob.Keys.Contains(dr["职位"].ToString().Trim()))
            {
                //UI.ShowError(string.Format("第{0}行的职位有错,请删除或输入正确的.", i));
                //return false;
                sbRes.Append("|职位有错,请删除或输入正确的");
            }
            if (dt.Columns.Contains("民族") && dr["民族"] != DBNull.Value && !string.IsNullOrEmpty(dr["民族"].ToString()) && !_DicNation.Keys.Contains(dr["民族"].ToString().Trim()))
            {
                //UI.ShowError(string.Format("第{0}行的民族有错,请删除或输入正确的.", i));
                //return false;
                sbRes.Append("|民族有错,请删除或输入正确的");
            }
            if (dt.Columns.Contains("学历") && dr["学历"] != DBNull.Value && !string.IsNullOrEmpty(dr["学历"].ToString()) && !_DicEdu.Keys.Contains(dr["学历"].ToString().Trim()))
            {
                //UI.ShowError(string.Format("第{0}行的学历有错,请删除或输入正确的.", i));
                //return false;
                sbRes.Append("|学历有错,请删除或输入正确的");
            }
            if (dt.Columns.Contains("工种") && dr["工种"] != DBNull.Value && !string.IsNullOrEmpty(dr["工种"].ToString()) && !_DicWorkType.Keys.Contains(dr["工种"].ToString().Trim()))
            {
                //UI.ShowError(string.Format("第{0}行的工种有错,请删除或输入正确的.", i));
                //return false;
                sbRes.Append("|工种有错,请删除或输入正确的");
            }
            if (dt.Columns.Contains("头像") && dr["头像"] != DBNull.Value && !string.IsNullOrEmpty(dr["头像"].ToString().Trim()))
            {
                if (!File.Exists(dr["头像"].ToString()))
                {
                    sbRes.Append("|头像路径不存在,请删除或输入正确的");
                }
            }
            if (sbRes.Length > 0)
            {
                dr["ErrTip"] = sbRes.Remove(0, 1).ToString();
                return false;
            }
            else
            {
                dr["ErrTip"] = DBNull.Value;
                return true;
            }
        }
    }
}
